#使用事件实现线程同步
import logging
import threading
import time
import random

LOG_FORMAT='%(asctime)s %(threadName)-17s %(levelname)-8s %(message)s'
logging.basicConfig(level=logging.INFO,format=LOG_FORMAT)
items=[]
event=threading.Event()

class Consumer(threading.Thread):#这里其实是consumer类继承了threading.Thread类
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)#这样执行超类，才可以访问超类的参数
    def run(self):
        while True:#一直在消费
            time.sleep(2)#消费的时间
            event.wait()#等待信号
            item=items.pop()
            logging.info('Consumer notify:{} consumed by {}'.format(item,self.name))
class Producer(threading.Thread):
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)#这样执行超类，才可以访问超类的参数
    def run(self):
        for i in range(5):#去生产五次，生产完成以后通知消费者
            time.sleep(2)
            item=random.randint(0,100)
            items.append(item)
            logging.info('Producer notify:item {} producted by {}'.format(item,self.name))
            event.set()#发送信号
            event.clear()#发送完信号以后清除，继续执行，否则会出现空元素的情况
def main():
    t1 = Producer()#此时的目标函数是class里面的run函数
    t2 = Consumer()

    t1.start()
    t2.start()

    t1.join()
    t2.join()

if __name__=='__main__':
    main()
